package org.sakila.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.sakila.entities.CommonResult;
import org.sakila.entities.Film;
import org.sakila.service.SakilaFeignService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class SakilaController {
    @Resource
    private SakilaFeignService sakilaFeignService;

    @GetMapping("/consumer/film/get/{id}")
    @SentinelResource(value = "getFilmById", blockHandler = "blockHandler", fallback = "fallbackHandler")
    public CommonResult<Film> getFilmById(@PathVariable("id") Long id) {
        if (id == 2) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
        }
        return sakilaFeignService.getFilmById(id);
    }

    @GetMapping("/consumer/film/getFilms/{start}/{size}")
    @SentinelResource(value = "getFilms", blockHandler = "blockHandler", fallback = "fallbackHandler")
    public CommonResult<?> getFilms(@PathVariable("start") Integer start, @PathVariable("size") Integer size) {
        return sakilaFeignService.getFilms(start, size);
    }

    public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
        Film film = new Film();
        return new CommonResult<>(445, "已被限流: blockException  " + blockException.getMessage(), film);
    }

    public CommonResult fallbackHandler(@PathVariable Long id, Throwable e) {
        Film film = new Film();
        return new CommonResult<>(444, "程序错误", film);
    }
}
